<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class Order extends Model
{
    protected $table = 'cdorder';
    protected $primaryKey = 'order_id';
    public $timestamps = false;
    protected $fillable = [];


    /*
     * 订单生成
     *
     * */

    public function orderAdd($orderData)
    {
        $mylog = new MyLog;
        $mylog->setLog($orderData['sign'] ,$logPath = 'voicedata');

        DB::beginTransaction();//事务
        try {
            $s_money = Wallet::where('openid', $orderData['openid'])->select('money')->first();

            $user = Member::where('open_id', $orderData['openid'])->first();
            $order = new  Order;
            $order->price = $orderData['formalities_momey'] - $s_money->money;//实际支付金额减去-账户零钱
            $order->order_sn = $this->trade_no();  //自己定义的订单编号
            $order->add_time = time();//下单时间
            $order->pay_time = time();//支付时间
            $order->uid = $user->id; //uid
            $order->number = $orderData['prize_num'];//红包数量
            $order->open_id = $user->open_id;
            $order->sign = $orderData['sign'];//标识
            if ($order->save()) {

                $voice_url = $order->sign==1 ? 0 : $orderData['voice_url'];
                $duration = $order->sign ==1 ? 0 : $orderData['duration'];
                $redf = DB::table('redf')->insert([
                    [
                        'order_sn' => $order->order_sn,
                        'uid' => $user->id,
                        'openid' => $orderData['openid'],
                        'price' => $orderData['prize_src'],//用户发红包价格+零钱价格,不包含服务费
                        's_price' => $orderData['prize_src'],
                        'number' => $order->number,
                        's_number' => $order->number,
                        'password' => $orderData['text'],//红包口令
                        'created_at' => time(),
                        'formid' => $orderData['formId'],
                        'sign'=>$orderData['sign'],//标识
                        'voice_url'=>$voice_url,
                        'duration'=>$duration,
                        'is_share' => $orderData['is_share'],//是否共享

                ],
                ]);
            }

            if ($order && $redf) {
                DB::commit();//成功，提交事务
                //echo 'success';
                return $order->order_sn;
            }
        } catch (\Exception $e) {
            $mylog = new MyLog;
            $mylog->setLog('数据异常:' . $order->order_sn . $e, $logPath = 'order');
            DB::rollBack();//失败，回滚事务
            //echo 'error';
            return false;
        }
    }


    /**
     * 生成订单号
     */
    private function trade_no()
    {
        list($usec, $sec) = explode(" ", microtime());
        $usec = substr(str_replace('0.', '', $usec), 0, 4);
        $str = rand(10, 99);
        return date("YmdHis") . $usec . $str;
    }


    /*
     * 用户零钱支付只走发红包表
     * */
    public function wallet_money($orderData)
    {

            $s_money = Wallet::where('openid', $orderData['openid'])->select('money')->first();
            if ($s_money->money >= $orderData['formalities_momey']) { //如果零钱大于支付金额执行下面的
                $voice_url = $orderData['sign']==1 ? 0 : $orderData['voice_url'];
                $duration = $orderData['sign'] ==1 ? 0 : $orderData['duration'];
                DB::beginTransaction();//事务
                try {
                $user = Member::where('open_id', $orderData['openid'])->select('id')->first();
                $redf = new  Redf;
                $redf->order_sn = $this->trade_no();//零钱支付订单号为1
                $redf->uid = $user->id;
                $redf->openid = $orderData['openid'];
                $redf->price = $orderData['prize_src'];//prize_src不包含零钱价格
                $redf->s_price = $orderData['prize_src'];
                $redf->number = $orderData['prize_num'];
                $redf->s_number = $orderData['prize_num'];
                $redf->password = $orderData['text'];
                $redf->formid = $orderData['formId'];
                $redf->status = 1;//1代表已支付
                $redf->pay_type = 1;//零钱支付
                $redf->sign =$orderData['sign'];//标识
                $redf->voice_url = $voice_url;
                $redf->duration = $duration;
                $redf->is_share = $orderData['is_share'];
                $redf->created_at = time();
                if ($redf->save()) {
                    //零钱支付减去钱包零钱  //实际支付金额减去-账户零钱
                    $wallet_update = DB::table('wallet')->where('openid', $orderData['openid'])->decrement('money', $orderData['formalities_momey']);
                }

                if ($redf && $wallet_update) {
                    DB::commit();//成功，提交事务
                    //echo 'success';
                    // $logs = Mongodb::connectionMongodb('hb_log');
                    // $logs->insert(['order_sn' =>$redf->order_sn, 'openid' =>  $redf->openid, 'type' => '4', 'name' => '零钱支付记录', 'message' => $redf->price, 'log_time' => date("Y-m-d H:i")]);

                    return ['redfid' => $redf->id, 'password' => $redf->password];
                }

            } catch (\Exception $e) {
                $mylog = new MyLog;
                $mylog->setLog('数据异常:' . $e, $logPath = 'orderMomey');
                DB::rollBack();//失败，回滚事务
                echo 'error';
                //return false;
            }
        }

        return false;
    }

    //猜对有钱语音上传
    public function cdvoiceUpload(){
        //文件上传
        $Path = "/public/voiceUpload/";
        if (!empty($_FILES['file'])) {
            //获取扩展名
            $exename = $this->getExeName($_FILES['file']['name']);
            $fileName = base_path() . $Path;//文件路径
            $savename = 'voice_' . date("YmdHis") . rand(0, 100);
            $upload_name =  $savename . '.' . $exename;//文件名加后缀
            if (!file_exists($fileName)) {
                //进行文件创建
                mkdir($fileName, 0777, true);
            }
            $imageSavePath = $fileName . $upload_name;
            if (move_uploaded_file($_FILES['file']['tmp_name'], $imageSavePath)) {//文件上传成功
               return $voice_url = 'https://hd.huwaishequ.com/kxred/public/voiceUpload/'.$upload_name;
            }else {
                return response()->json(['code' => 200, 'status' => 0, 'message' => '文件上传失败']);
            }
        }
    }

    public function getExeName($fileName)
    {
        $pathinfo = pathinfo($fileName);
        return strtolower($pathinfo['extension']);
    }
}
